<template>
	<!-- <view class="yst-print p-btn" @click="clickPrintBtn"> -->
	<view class="yst-print p-btn" @click="_checkOverTime">
		<view class="">打印</view>
	</view>
</template>

<script>
	import tsc from '@/utils/tsc.js';
	export default {
		props: ['getCheckedList', 'show'],
		data() {
			return {
				app: {},

				dataList: [],
				checdedTotal: 0,
				printingNum: 0,

				looptime: 0,
				currentTime: 1,
				lastData: 0,
				oneTimeData: 0,
				buffSize: [],
				buffIndex: 0, //发送字节数下标
				printNum: [],
				printNumIndex: 0,
				printerNum: 1,
				currentPrint: 1,
				isLabelSend: false,
				isQuery: false,
				imageSrc: '',
				jpgSrc: '',
				canvasWidth: 100,
				canvasHeight: 100,
				jpgWidth: 200,
				jpgHeight: 200,

				textNum: 0,
			}
		},
		created() {
			this.app = getApp();
			this.initPriter();
		},

		watch: {

		},

		methods: {
			// 模仿微信小程序setData
			setData(obj) {
				Object.assign(this, obj);
			},

			/**
			 * 生命周期函数--监听页面初次渲染完成
			 */
			onReady: function() {
				// this.initPriter();
			},

			// 初始化打印机  
			initPriter: function() {
				var list = []
				var numList = []
				var j = 0
				for (var i = 20; i < 200; i += 10) {
					list[j] = i;
					j++
				}
				for (var i = 1; i < 10; i++) {
					numList[i - 1] = i
				}
				this.setData({
					buffSize: list,
					oneTimeData: list[0],
					printNum: numList,
					printerNum: numList[0]
				})
				this.initPhoto();
			},
			//接单时间检测
			_checkOverTime() {
				this.$emit('checkOverTime');
			},
			// 点击打印按钮
			clickPrintBtn() {
				var _this = this;
				var queryPrinterStatus = this.app.globalData.queryPrinterStatus
				// this.printPhoto()	// 调试，可删除
				queryPrinterStatus({
					successCallback: () => {
						// 打印机状态正常，则获取数据，开始打印
						_this.$emit('getCheckedList', (list) => {
							_this.dataList = list;

							// _this.getDataList(); // 调试，可删除，开启后打印假数据
							// _this.printPhoto();  // 调试，可删除

							_this.printData();
						})
					},
					failCallback: () => {
						uni.showToast({
							title: '正在连接打印机，请稍后打印',
							icon: 'none',
							duration: 3000
						})
						return;
					}
				})

			},

			// 获取数据
			getDataList: function() {
				var list = [{
						id: "16711549517090775056",
						pickingSerialNo: '999',
						supplyAddress: 'A18',
						nameTakingMeal: '张明控制台',
						nameDishes: '豆蒸排骨( 不辣 +保鸡丁(  ) +小白菜+米饭x1',
						remarks: '小白菜+米饭sdsfdsdfsdf',
						orderTime: '09:02:01',
					},
					/* {
						id: "167115ty775057",
						pickingSerialNo: '135',
						supplyAddress: 'A18',
						nameTakingMeal: '张明张明张明',
						nameDishes: '豆蒸排骨( 不辣 +保鸡丁(  ) +小白菜+米饭x1',
						remarks: '第2份',
						orderTime: '09:02:01',
					},{
						id: "167tt75057",
						pickingSerialNo: '135',
						supplyAddress: 'A18',
						nameTakingMeal: '张明33',
						nameDishes: '豆蒸排骨( 不辣 +保鸡丁(  ) +小白菜+米饭x1',
						remarks: '第2份',
						orderTime: '09:02:01',
					}, */
				]

				this.setData({
					dataList: list
				})
			},

			// 执行打印
			printData: function() {
				if (this.isLabelSend) {
					return;
				}
				var _this = this;

				// 控制打印时间
				var _time = '10:00:00'
				var date = new Date();
				var year = date.getFullYear();
				var month = date.getMonth() + 1;
				var day = date.getDate();
				var date2 = year + '/' + month + '/' + day + ' ' + _time;
				var printTime = new Date(date2);
				if (date <= printTime && false) {
					uni.showModal({
						title: '提示',
						content: '请在10:00后打印',
						showCancel: false
					})
					return;
				}

				var list = this.dataList;
				if (list.length == 0) {
					uni.showToast({
						title: '请选择要打印的订单',
						icon: 'none'
					})
					return;
				}

				// 检查设备连接状况
				// todo

				uni.showModal({
					title: '提示',
					content: '确定打印选中的' + list.length + '个订单？',
					complete: (res) => {
						if (res.confirm) {
							_this.setData({
								printingNum: 0
							})
							_this.setData({
								isLabelSend: true
							})
							this.$emit('setPrintData')
							print();
						}
					}
				})


				function print() {
					var i = _this.printingNum;
					console.log(i);
					uni.showLoading({
						title: '打印中...' + (i + 1),
					})
					_this.printLabel(list[i]);

					_this.setData({
						printingNum: i + 1
					})
					if (_this.printingNum < list.length) {
						setTimeout(() => {
							print();
						}, 2000)
					} else {
						setTimeout(() => {
							uni.hideLoading();
							_this.setData({
								isLabelSend: false
							})
						}, 400);
						// }, _this.app.globalData.printSet.speed2);
					}
				}

			},

			// --------------------------------------

			initPhoto: function() { //初始化画布数据
				//创建一个png格式
				var that = this
				const ctx_out = uni.createCanvasContext('canvasOut', this);
				var png = that.imageSrc;
				uni.getImageInfo({
					src: png,
					success(res) {
						that.setData({
							canvasWidth: res.width,
							canvasHeight: res.height,
						});
						console.log("画布宽度" + res.width, "画布高度" + res.height);
						ctx_out.drawImage(png, 0, 0);
						ctx_out.draw();
					}
				})
				//创建一个jpg格式图片
				const ctx_jpg = uni.createCanvasContext('canvasJPG', this);
				var img = that.jpgSrc;
				uni.getImageInfo({
					src: img,
					success(res) {
						that.setData({
							jpgWidth: res.width,
							jpgHeight: res.height,
						});
						console.log("JPG画布宽度" + res.width, "JPG画布高度" + res.height);
						ctx_jpg.drawImage(img, 0, 0, res.width, res.height);
						ctx_jpg.draw();
					}
				})
			},


			// 标签打印
			printLabel: function(item) {
				var that = this;
				var command = tsc.jpPrinter.createNew()
				this.setPrintText(command, item);

				// -------
				// var setting = this.app.globalData.printSet
				// command.setSpeed(setting.speed)
				// command.setDensity(setting.density)
				// command.setGap(setting.gap)
				// command.setSize(setting.width, setting.height)
				// -------

				command.setPagePrint() // 执行打印指令
				that.prepareSend(command.getData())
				console.log(item.id);
			},

			// 设置打印的标签
			setPrintText: function(command, item) {
				command.setCls() //清除缓冲区，防止下一个没生效。不能少！！
				command.setSize(58, 30) //设置标签大小，单位mm.具体参数请用尺子量一下
				command.setSpeed(4) // 打印速度1-6，越大越快
				command.setGap(0) //设置两个标签之间的间隙，单位mm.具体参数请用尺子量一下（默认是0，技术员说至少设置2）
				command.setCls() //清除缓冲区

				var setting = this.app.globalData.printSet
				if (setting.setBox.x1 == 8) {
					// command.setBox(10, 10, 464, 230, 5)//绘制一个边框
					// command.setBar(10, 75, 455, 5);//绘制一条黑线
				}

				// 0810新的标签打印
				if (1 == 0) {
					var {
						addr,
						name,
						num,
						cai,
						desc,
						time
					} = setting;
					let nameTakingMeal = item.nameTakingMeal.substr(0, 4);
					command.setText(addr.x, addr.y, "TSS24.BF2", 0, 3, 3, "地址:" + item.supplyAddress) //绘制文字
					command.setText(name.x, name.y, "TSS24.BF2", 0, 2, 2, "姓名:" + nameTakingMeal) //绘制文字
					command.setText(num.x, num.y, "TSS24.BF2", 0, 2, 2, item.pickingSerialNo) // 序号
					command.setText(cai.x, cai.y, "TSS24.BF2", 0, 1, 1, "菜品:" + item.nameDishes) //绘制文字
					command.setText(desc.x, desc.y, "TSS24.BF2", 0, 1, 1, "备注666:" + (item.remarks || '')) //绘制文字
					let timeList = item.createTime.split(' ');
					let createTime = timeList[0].split('-')[1] + '-' + timeList[0].split('-')[2] + ' ' + timeList[1]
					command.setText(time.x, time.y, "TSS24.BF2", 0, 1, 1, createTime) //下单时间
					return;
				}

				// 备份--原来的标签打印
				/* command.setText(90, 36, "TSS24.BF2", 0, 2, 2, "地址:" + item.supplyAddress) //绘制文字
				command.setText(30, 125, "TSS24.BF2", 0, 1, 1, "序号:" + item.pickingSerialNo) //绘制文字
				command.setText(370, 125, "TSS24.BF2", 0, 2, 2, "姓名:" + item.nameTakingMeal) //绘制文字
				command.setText(30, 195, "TSS24.BF2", 0, 1, 1, "菜品:" + item.nameDishes) //绘制文字
				command.setText(30, 260, "TSS24.BF2", 0, 2, 2, "备注:" + (item.remarks || '')) //绘制文字 */

				let nameTakingMeal = item.nameTakingMeal.substr(0, 4);
				command.setText(30, 36, "TSS24.BF2", 0, 3, 3, "地址:" + item.supplyAddress) //绘制文字
				command.setText(30, 125, "TSS24.BF2", 0, 2, 2, "姓名:" + nameTakingMeal) //绘制文字
				command.setText(370, 125, "TSS24.BF2", 0, 2, 2, item.pickingSerialNo) // 序号
				command.setText(30, 195, "TSS24.BF2", 0, 1, 1, "菜品:" + item.nameDishes) //绘制文字
				command.setText(30, 260, "TSS24.BF2", 0, 1, 1, "备注:" + (item.remarks || '')) //绘制文字
				let timeList = item.createTime.split(' ');
				let createTime = timeList[0].split('-')[1] + '-' + timeList[0].split('-')[2] + ' ' + timeList[1]
				command.setText(250, 300, "TSS24.BF2", 0, 1, 1, createTime) //绘制文字 //下单时间
			},

			// 打印bitmap，图片内容不建议太大，小程序限制传输的字节数为20byte
			printPhoto: function() {
				var _this = this;
				var setting = this.app.globalData.printSet;

				this.textNum++;
				if (this.textNum == setting.printNum + 1) {
					this.textNum = 0;
					return;
				}


				var {
					addr,
					name,
					num,
					cai,
					desc,
					time
				} = setting;
				var data = [{
						label: '地址：',
						content: 'A25'
					},
					{
						label: '姓名：',
						content: '王小二'
					},
					{
						label: '',
						content: '268'
					},
					{
						label: '菜品：',
						content: '豆蒸排骨( 不辣 +保鸡丁(  ) +小白菜+米饭x1'
					},
					{
						label: '备注：',
						content: '我要变态辣'
					},
				]

				var width = setting.width2 * 10;
				var height = setting.height2 * 10;
				const canvas = wx.createOffscreenCanvas({
					type: '2d',
					width: width,
					height: height
				})
				const ctx = canvas.getContext('2d')
				// ctx.fillStyle = '#000000';
				ctx.fillStyle = '#ffffff';
				ctx.fillRect(0, 0, width, height);
				ctx.fillStyle = '#ffffff';

				[addr, name, num, cai, desc, time].forEach((attrObj, index) => {
					var msgObj = data[index];
					ctx.font = attrObj.size + 'px';
					let msg = msgObj.label + msgObj.content;
					ctx.fillText(msg, attrObj.x, attrObj.y);
					// ctx.fillText(msg, 50, 50);
				})

				var imageData = ctx.getImageData(0, 0, width, height)
				console.log(imageData)

				var command = tsc.jpPrinter.createNew()
				command.setCls()
				command.setSize(setting.width, setting.height)
				command.setGap(0)
				command.setCls()

				command.setBitmap(0, 0, 0, imageData)
				command.setPrint(1)
				console.log('----开始打图')
				this.prepareSend(command.getData()) //发送数据
			},

			prepareSend: function(buff) { //准备发送，根据每次发送字节数来处理分包数量
				// console.log('buff',buff)
				var that = this
				var time = that.oneTimeData
				var looptime = parseInt(buff.length / time);
				var lastData = parseInt(buff.length % time);
				//console.log(looptime + "---" + lastData)
				that.setData({
					looptime: looptime + 1,
					lastData: lastData,
					currentTime: 1,
				})
				that.Send(buff)
			},

			// ArrayBuffer转16进度字符串
			ab2hex(buffer) {
				var hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('');
			},

			// 查询/监听打印机状态
			queryStatus: function() {
				var that = this
				var buf;
				var dateView;
				/*
				n = 1：传送打印机状态
				n = 2：传送脱机状态
				n = 3：传送错误状态
				n = 4：传送纸传感器状态
				*/
				buf = new ArrayBuffer(5)
				dateView = new DataView(buf)
				dateView.setUint8(0, 27)
				dateView.setUint8(1, 33)
				dateView.setUint8(2, 63)
				dateView.setUint8(3, 13)
				dateView.setUint8(4, 10)
				uni.writeBLECharacteristicValue({
					deviceId: that.app.globalData.BLEInformation.deviceId,
					serviceId: that.app.globalData.BLEInformation.writeServiceId,
					characteristicId: that.app.globalData.BLEInformation.writeCharaterId,
					value: buf,
					success: function(res) {
						console.log("发送成功", res)
						that.setData({
							isQuery: true
						})
					},
					fail: function(e) {
						uni.showToast({
							title: '发送失败',
							icon: 'none',
						})
						//console.log(e)
						return;
					},
					complete: function() {

					}
				})

				uni.notifyBLECharacteristicValueChange({
					deviceId: that.app.globalData.BLEInformation.deviceId,
					serviceId: that.app.globalData.BLEInformation.notifyServiceId,
					characteristicId: that.app.globalData.BLEInformation.notifyCharaterId,
					state: true,
					success: function(res) {
						uni.onBLECharacteristicValueChange(function(r) {
							console.log(
								`characteristic ${r.characteristicId} has changed, now is ${r}`
							)
							var result = that.ab2hex(r.value)
							console.log("返回" + result)
							var tip = ''
							if (result == 0) { //正常
								tip = "正常"
							} else if (result == 4) { //缺纸
								tip = "缺纸"
							} else if (result == 5) { //开盖、缺纸
								tip = "开盖、缺纸"
							} else if (result == 41) {
								tip = "开盖"
							} else if (result == 40) { //其他错误
								tip = "其他错误"
							} else { //未处理错误
								tip = "未知错误"
							}
							uni.showModal({
								title: '打印机状态',
								content: tip,
								showCancel: false
							})

						})
					},
					fail: function(e) {
						// 获取打印机状态失败，说明不能打印
						uni.showModal({
							title: '打印机状态',
							content: '连接异常，请重新连接',
							showCancel: false
						})
						console.log(e)
						// 需要重置打印机状态为未连接
						that.app.globalData.setConnectedDevice();

					},
					complete: function(e) {
						that.setData({
							isQuery: false
						})
						console.log("执行完成")
					}
				})
			},

			// 分包发送
			Send: function(buff) {
				var that = this
				var currentTime = that.currentTime
				var loopTime = that.looptime
				var lastData = that.lastData
				var onTimeData = that.oneTimeData
				var printNum = that.printerNum
				var currentPrint = that.currentPrint
				var buf
				var dataView
				if (currentTime < loopTime) {
					buf = new ArrayBuffer(onTimeData)
					dataView = new DataView(buf)
					for (var i = 0; i < onTimeData; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
					}
				} else {
					buf = new ArrayBuffer(lastData)
					dataView = new DataView(buf)
					for (var i = 0; i < lastData; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
					}
				}
				// console.log("第" + currentTime + "次发送数据大小为："+ buf.lenght)
				// 小程序不会对写入数据包大小做限制，但系统与蓝牙设备会限制蓝牙 4.0 单次传输的数据大小，超过最大字节数后会发生写入错误，建议每次写入不超过 20 字节。
				uni.writeBLECharacteristicValue({
					deviceId: that.app.globalData.BLEInformation.deviceId,
					serviceId: that.app.globalData.BLEInformation.writeServiceId,
					characteristicId: that.app.globalData.BLEInformation.writeCharaterId,
					value: buf,
					success: function(res) {
						if (currentPrint == printNum) {
							/* uni.showToast({
							  title: '已打印第' + currentPrint + '张',
							}) */
						}
					},
					fail: function(e) {
						console.log(e, '第' + currentPrint + '张失败', )
					},
					complete: function() {
						currentTime++
						if (currentTime <= loopTime) {
							that.currentTime = currentTime;
							that.Send(buff)
						} else {
							// uni.showToast({
							//   title: '已打印第' + currentPrint + '张',
							// })`
							if (currentPrint == printNum) {
								that.setData({
									looptime: 0,
									lastData: 0,
									currentTime: 1,
									//   isLabelSend: false,
									currentPrint: 1
								})
								console.log('一个打印至此结束')

								setTimeout(() => {
									// that.printLabel(that.dataList[that.printingNum])
								}, 200)
								// that.printPhoto()  // 调试，可删除。从这里循环打印怎么样
							} else {
								currentPrint++
								that.setData({
									currentPrint: currentPrint,
									currentTime: 1,
								})
								that.Send(buff)
							}
						}
					}
				})
			},



			/**
			 * 生命周期函数--监听页面显示
			 */
			onShow: function() {

			},


			buffBindChange: function(res) { //更改打印字节数
				var index = res.detail.value
				var time = this.buffSize[index]
				this.setData({
					buffIndex: index,
					oneTimeData: time
				})
			},
			printNumBindChange: function(res) { //更改打印份数
				var index = res.detail.value
				var num = this.printNum[index]
				this.setData({
					printNumIndex: index,
					printerNum: num
				})
			},
		}

	}
</script>

<style lang="scss">
	/* .yst-print.p-btn {
		display: flex;
		view {
			background-color: indianred;
			margin-right: 10rpx;
		}
	} */
</style>